<script setup lang="ts">
import { ref } from 'vue'
import { getApiUrl } from './config'

const selectedFile = ref<File | null>(null)
const selectedConversion = ref<string>('wordToPdf')
const uploadProgress = ref<number>(0)
const isProcessing = ref<boolean>(false)
const conversionResult = ref<string | null>(null)
const errorMessage = ref<string | null>(null)

// 处理文件选择
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    selectedFile.value = target.files[0]
    errorMessage.value = null
  }
}

// 验证文件类型
const validateFile = (): boolean => {
  if (!selectedFile.value) {
    errorMessage.value = '请选择一个文件'
    return false
  }
  
  if (selectedConversion.value === 'wordToPdf' || selectedConversion.value === 'wordToImage') {
    const validTypes = ['.docx', '.doc']
    const fileExtension = selectedFile.value.name.split('.').pop()?.toLowerCase()
    if (!fileExtension || !validTypes.includes('.' + fileExtension)) {
      errorMessage.value = '请选择Word文档(.docx或.doc)'
      return false
    }
  } else if (selectedConversion.value === 'pdfToImage' || 
             selectedConversion.value === 'pdfToWord' || 
             selectedConversion.value === 'pdfToExcel' || 
             selectedConversion.value === 'pdfToPpt') {
    if (!selectedFile.value.name.toLowerCase().endsWith('.pdf')) {
      errorMessage.value = '请选择PDF文件'
      return false
    }
  } else if (selectedConversion.value === 'excelToImage') {
    const validTypes = ['.xlsx', '.xls']
    const fileExtension = selectedFile.value.name.split('.').pop()?.toLowerCase()
    if (!fileExtension || !validTypes.includes('.' + fileExtension)) {
      errorMessage.value = '请选择Excel文档(.xlsx或.xls)'
      return false
    }
  } else if (selectedConversion.value === 'pptToImage') {
    const validTypes = ['.pptx', '.ppt']
    const fileExtension = selectedFile.value.name.split('.').pop()?.toLowerCase()
    if (!fileExtension || !validTypes.includes('.' + fileExtension)) {
      errorMessage.value = '请选择PPT文档(.pptx或.ppt)'
      return false
    }
  }
  
  return true
}

// 上传文件并进行转换
const handleConvert = async () => {
  if (!validateFile()) {
    return
  }
  
  isProcessing.value = true
  uploadProgress.value = 0
  errorMessage.value = null
  conversionResult.value = null
  
  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value!)
    formData.append('conversion_type', selectedConversion.value)
    
    const response = await fetch(getApiUrl('/convert'), {
      method: 'POST',
      body: formData,
      headers: {
        'Accept': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('转换失败，请重试')
    }
    
    const data = await response.json()
    
    if (selectedConversion.value === 'wordToPdf' || 
        selectedConversion.value === 'pdfToWord' || 
        selectedConversion.value === 'pdfToExcel' || 
        selectedConversion.value === 'pdfToPpt') {
      // 对于单文件结果，创建下载链接
      const blob = await (await fetch(getApiUrl('/download', data.filename))).blob()
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = data.filename
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      let successMessage = ''
      switch(selectedConversion.value) {
        case 'wordToPdf':
          successMessage = 'PDF转换成功，文件已下载'
          break
        case 'pdfToWord':
          successMessage = 'Word转换成功，文件已下载'
          break
        case 'pdfToExcel':
          successMessage = 'Excel转换成功，文件已下载'
          break
        case 'pdfToPpt':
          successMessage = 'PPT转换成功，文件已下载'
          break
      }
      conversionResult.value = successMessage
    } else if (selectedConversion.value === 'pdfToImage' || 
               selectedConversion.value === 'wordToImage' || 
               selectedConversion.value === 'excelToImage' || 
               selectedConversion.value === 'pptToImage') {
      // 对于图片结果，显示图片链接
      conversionResult.value = `图片转换成功，共生成 ${data.image_count} 张图片。\n`
      data.image_files.forEach((filename: string, index: number) => {
        conversionResult.value += `图片 ${index + 1}: ${getApiUrl('/download', filename)}\n`
      })
    }
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '转换失败，请检查后端服务是否运行'
  } finally {
    isProcessing.value = false
    uploadProgress.value = 100
  }
}
</script>

<template>
  <div class="app-container">
    <h1>文档转换系统</h1>
    
    <div class="conversion-panel">
      <div class="conversion-options">
        <label>
          <input
            type="radio"
            value="wordToPdf"
            v-model="selectedConversion"
          />
          Word 转 PDF
        </label>
        <label>
          <input
            type="radio"
            value="pdfToImage"
            v-model="selectedConversion"
          />
          PDF 转图片
        </label>
        <label>
          <input
            type="radio"
            value="pdfToWord"
            v-model="selectedConversion"
          />
          PDF 转 Word
        </label>
        <label>
          <input
            type="radio"
            value="pdfToExcel"
            v-model="selectedConversion"
          />
          PDF 转 Excel
        </label>
        <label>
          <input
            type="radio"
            value="pdfToPpt"
            v-model="selectedConversion"
          />
          PDF 转 PPT
        </label>
        <label>
          <input
            type="radio"
            value="wordToImage"
            v-model="selectedConversion"
          />
          Word 转图片
        </label>
        <label>
          <input
            type="radio"
            value="excelToImage"
            v-model="selectedConversion"
          />
          Excel 转图片
        </label>
        <label>
          <input
            type="radio"
            value="pptToImage"
            v-model="selectedConversion"
          />
          PPT 转图片
        </label>
      </div>
      
      <div class="file-upload">
        <input
          type="file"
          @change="handleFileChange"
          :disabled="isProcessing"
          class="file-input"
        />
        <div v-if="selectedFile" class="file-info">
          已选择: {{ selectedFile.name }}
        </div>
      </div>
      
      <button
        @click="handleConvert"
        :disabled="isProcessing || !selectedFile"
        class="convert-btn"
      >
        {{ isProcessing ? '处理中...' : '开始转换' }}
      </button>
      
      <div v-if="uploadProgress > 0" class="progress-bar">
        <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
      </div>
      
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
      
      <div v-if="conversionResult" class="result-message">
        {{ conversionResult }}
      </div>
    </div>
    
    <div class="usage-guide">
        <h3>使用说明</h3>
        <ol>
          <li>选择要进行的转换类型：Word转PDF、PDF转图片、PDF转Word、PDF转Excel、PDF转PPT</li>
          <li>点击"选择文件"按钮，上传相应的文件</li>
          <li>点击"开始转换"按钮，等待转换完成</li>
          <li>转换成功后，结果将自动下载（PDF、Word、Excel、PPT）或显示下载链接（图片）</li>
        </ol>
      </div>
  </div>
</template>

<style scoped>
.app-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
}

.conversion-panel {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.conversion-options {
  margin-bottom: 20px;
}

.conversion-options label {
  display: block;
  margin-bottom: 10px;
  cursor: pointer;
}

.file-upload {
  margin-bottom: 20px;
}

.file-input {
  margin-bottom: 10px;
}

.file-info {
  font-size: 14px;
  color: #666;
}

.convert-btn {
  background-color: #42b883;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.convert-btn:hover:not(:disabled) {
  background-color: #35495e;
}

.convert-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 10px;
  margin: 20px 0;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #42b883;
  transition: width 0.3s;
}

.error-message {
  color: #e74c3c;
  margin-top: 15px;
}

.result-message {
  color: #2ecc71;
  margin-top: 15px;
  white-space: pre-line;
}

.usage-guide {
  margin-top: 40px;
  padding: 20px;
  background-color: #f0f0f0;
  border-radius: 8px;
}

.usage-guide ol {
  margin-top: 10px;
  padding-left: 20px;
}

.usage-guide li {
  margin-bottom: 8px;
}
</style>
